/**
 * Data: 2018/06/11
 * Auth: Dongyunlong
 * Desc: 自定义颜色选择器
 */
var context;//画布
var width, height;
var colorArr = ['#FE7163', '#FFAE56', '#FFFF4D', '#60FF50', '#58FFE9', '#51E0FF', '#9C42FF', '#FF5664'];
var padding = 16;

//定义Point
var Point = function (x, y) {
	return { x: x, y: y };
};
//定义Rect
var Rect = function (x, y, w, h) {
	return { x: x, y: y, width: w, height: h };
}

Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		width: {
			type: Number,
			value: 240,
		},
		height: {
			type: Number,
			value: 30,
		},
	},

	/**
	 * 组件的初始数据
	 */
	data: {

	},

	/**
	 * 组件生命周期函数，在组件布局完成后执行，此时可以获取节点信息
	 */
	ready: function () {
		context = wx.createCanvasContext('canvasView', this);
		wx.getSystemInfo({
			success: function (res) {
				width = res.windowWidth / 3 * 2 - padding * 2 - 4;
			},
		})
		// width = this.properties.width;
		height = this.properties.height - 4;
		console.log(width + '/' + height);
		//绘制
		draw(0, height / 2, context, context);
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		//按下事件
		touchStart: function (e) {

		},
		//滑动事件
		touchMove: function (e) {
			console.log(e.changedTouches[0].x);
			draw(e.changedTouches[0].x, height / 2, context);
		},
		//结束时间
		touchEnd: function (e) {
			console.log(e.changedTouches[0].x + '/' + height / 2);
			draw(e.changedTouches[0].x, height / 2, context);
			wx.canvasGetImageData({
				canvasId: 'canvasView',
				x: e.changedTouches[0].x,
				y: height / 2,
				width: 1,
				height: 1,
				success(res) {
					console.log(res);
					console.log(res.data instanceof Uint8ClampedArray) // true
					var c = res.data;
					var red = c[0];
					var green = c[1];
					var blue = c[2];
					console.log(red + '/' + green + '/' + blue);
				}
			}, this);
		}
	},
})
//绘制背景
function drawBg(context) {
	//创建线性渐变
	var grd = context.createLinearGradient(0, 0, width, 0);
	for (var i = 0; i < colorArr.length; i++) {
		grd.addColorStop(i * (1 / (colorArr.length - 1)), colorArr[i]);
	}
	//开启路径
	context.beginPath();
	//设置渐变
	context.setFillStyle(grd);
	context.setFillStyle(grd);
	//绘制圆角矩形
	var r = height / 2;//圆角半径
	var rect = Rect(0, 0, width, height);
	var ptA = Point(rect.x + r, rect.y);
	var ptB = Point(rect.x + rect.width, rect.y);
	var ptC = Point(rect.x + rect.width, rect.y + rect.height);
	var ptD = Point(rect.x, rect.y + rect.height);
	var ptE = Point(rect.x, rect.y);
	context.beginPath();
	context.moveTo(ptA.x, ptA.y);
	context.arcTo(ptB.x, ptB.y, ptC.x, ptC.y, r);
	context.arcTo(ptC.x, ptC.y, ptD.x, ptD.y, r);
	context.arcTo(ptD.x, ptD.y, ptE.x, ptE.y, r);
	context.arcTo(ptE.x, ptE.y, ptA.x, ptA.y, r);
	//关闭路径
	context.closePath();
	//填充
	context.fill();
	// context.stroke();

}
//绘制按钮圆
function drawRound(x, y, context) {
	// Draw arc
	context.beginPath();
	context.arc(x, y, 10, 0, 360);
	context.setFillStyle('#ffffff');
	context.fill();
}
//绘制
function draw(x, y, context) {
	drawBg(context);
	drawRound(x, y, context);
	context.draw();
}

